<!-- TravelJournalEditor.vue -->
<!-- 编辑个人游记页面 -->
<template>
  <div class="travel-journal-editor">
    <nav-bar :activeComponent="activeComponent"></nav-bar>
    <!-- 封面区域 - 保持宽度100% -->
    <div class="cover-container">
      <div class="cover-image" :style="{ backgroundImage: `url(${coverImage})` }">
        <button class="upload-button" @click="triggerCoverUpload">
          <i class="fas fa-upload"></i> 上传封面
        </button>
        <input
            type="file"
            ref="coverUpload"
            @change="handleCoverUpload"
            accept="image/*"
            class="hidden-input"
        />
      </div>
    </div>

    <div class="editor-layout">
      <!-- 正文区域 - 现在变窄了 -->
      <div class="content-container">
        <!-- 标签编辑区 -->
        <div class="tags-container">
          <div class="selected-tags">
            <el-tag
                v-for="(tag, index) in selectedTags"
                :key="tag.id"
                :type="tag.type"
                closable
                @close="removeTag(index)"
                class="tag-item"
            >
              {{ tag.name }}
            </el-tag>
          </div>

          <button class="select-tags-button" @click="showDialog">
            <i class="el-icon-plus"></i> 选择标签
          </button>

          <!-- 标签选择弹窗 -->
          <el-dialog
              title="选择标签"
              v-model="showTagSelector"
              width="500px"
              center
          >
            <div class="tag-search">
              <input
                  v-model="tagFilter"
                  class="tag-search-input"
                  placeholder="搜索标签"
              />
            </div>

            <div class="tag-options">
              <el-tag
                  v-for="tag in filteredTags"
                  :key="tag.id"
                  :type="tag.type"
                  class="tag-option"
                  @click="selectTag(tag)"
              >
                {{ tag.name }}
              </el-tag>

              <div v-if="filteredTags.length === 0" class="no-tags-found">
                没有找到匹配的标签
              </div>
            </div>

            <template #footer>
      <span class="dialog-footer">
        <el-button @click="showTagSelector = false">关闭</el-button>
      </span>
            </template>
          </el-dialog>
        </div>
        <!-- 标题输入区 -->
        <div class="title-container" @click="focusTitle">
          <input
              ref="titleInput"
              v-model="title"
              class="title-input"
              :placeholder="titleFocused ? '' : '输入标题'"
              @focus="titleFocused = true"
              @blur="handleTitleBlur"
          />
        </div>

        <!-- 正文段落区域 -->
        <div class="paragraphs-container">
          <transition-group name="paragraph-move" tag="div">
            <div
                v-for="(paragraph, index) in paragraphs"
                :key="'p-' + index"
                class="paragraph-block"
                :id="getParagraphId(paragraph, index)"
                :class="{ 'is-dragging': draggedIndex === index }"
                draggable="true"
                @dragstart="startDrag($event, index)"
                @dragover.prevent="onDragOver($event, index)"
                @dragenter.prevent="onDragEnter($event, index)"
                @dragleave="onDragLeave($event)"
                @drop.prevent="onDrop($event, index)"
                @dragend="endDrag"
            >
              <!-- 段落工具栏 -->
              <div class="paragraph-tools">
                <button class="tool-button add-button" @click="addParagraph(index)" title="添加段落">
                  <i class="fas fa-plus"></i>
                </button>
                <button class="tool-button move-up" @click="moveParagraph(index, -1)" :disabled="index === 0" title="上移">
                  <i class="fas fa-chevron-up"></i>
                </button>
                <button class="tool-button move-down" @click="moveParagraph(index, 1)" :disabled="index === paragraphs.length - 1" title="下移">
                  <i class="fas fa-chevron-down"></i>
                </button>
                <button class="tool-button settings-button" @click="openSettings(index)" title="设置格式">
                  <i class="fas fa-cog"></i>
                </button>
                <button class="tool-button delete-button" @click="deleteParagraph(index)" :disabled="paragraphs.length <= 1" title="删除段落">
                  <i class="fas fa-trash"></i>
                </button>
              </div>

              <!-- 段落内容 -->
              <div class="paragraph-content">
                <!-- 文本段落 -->
                <div v-if="paragraph.type === 'text'" class="text-paragraph">
                  <textarea
                      v-if="paragraph.format === 'normal'"
                      v-model="paragraph.content"
                      class="paragraph-textarea"
                      placeholder="输入正文..."
                  ></textarea>
                  <div
                      v-else
                      :class="['heading-paragraph', `heading-${paragraph.format}`]"
                  >
                    <textarea
                        v-model="paragraph.content"
                        :class="['heading-textarea', `heading-${paragraph.format}`]"
                        :placeholder="`输入${paragraph.format}级标题...`"
                    ></textarea>
                  </div>
                </div>
                <!-- 小贴士段落 -->
                <div v-else-if="paragraph.type === 'tip'" class="tip-editor">
                  <div class="tip-header">
                    <i class="el-icon-info"></i>
                    <span>旅行小贴士</span>
                  </div>
                  <textarea
                      v-model="paragraph.content"
                      class="tip-textarea"
                      placeholder="输入小贴士内容..."
                  ></textarea>
                </div>

                <!-- 名人名言段落 -->
                <div v-else-if="paragraph.type === 'quote'" class="quote-editor">
                  <textarea
                      v-model="paragraph.content"
                      class="quote-textarea"
                      placeholder="输入名人名言..."
                  ></textarea>
                  <input
                      v-model="paragraph.author"
                      type="text"
                      class="author-input"
                      placeholder="作者（可选）"
                  >
                </div>

                <!-- 图片段落（修改后的图片段落） -->
                <div v-else-if="paragraph.type === 'image'" class="image-editor">
                  <div class="layout-selector">
                    <button
                        v-for="layout in imageLayouts"
                        :key="layout.value"
                        @click="changeImageLayout(paragraph, layout.value)"
                        :class="{ active: paragraph.layout === layout.value }"
                    >
                      <i :class="layout.icon"></i>
                      {{ layout.label }}
                    </button>
                  </div>

                  <div class="image-grid" :class="'layout-' + paragraph.layout">
                    <div
                        v-for="(img, idx) in paragraph.images"
                        :key="idx"
                        class="image-item"
                        v-show="idx < getImageCountForLayout(paragraph.layout)"
                    >
                      <div class="image-wrapper">
                        <img v-if="img.url" :src="img.url" alt="上传图片" class="fit-image">
                        <div v-else class="upload-area" @click="triggerImageUpload(index, idx)">
                          <i class="el-icon-plus"></i>
                        </div>
                        <input
                            type="file"
                            :ref="`imageUpload${index}_${idx}`"
                            @change="(e) => handleImageUpload(e, index, idx)"
                            accept="image/*"
                            class="hidden-input"
                        >
                      </div>
                      <input
                          v-model="img.caption"
                          type="text"
                          class="caption-input"
                          placeholder="图片注解"
                      >
                    </div>
                  </div>
                </div>

                <!-- 视频段落 -->
                <div v-else-if="paragraph.type === 'video'" class="video-paragraph">
                  <div v-if="paragraph.content" class="video-preview">
                    <video controls>
                      <source :src="paragraph.content" />
                      您的浏览器不支持视频播放
                    </video>
                  </div>
                  <div v-else class="video-upload" @click="triggerVideoUpload(index)">
                    <i class="fas fa-video"></i>
                    <span>点击上传视频</span>
                    <input
                        type="file"
                        :ref="`videoUpload${index}`"
                        @change="(e) => handleVideoUpload(e, index)"
                        accept="video/*"
                        class="hidden-input"
                    />
                  </div>
                </div>
              </div>
            </div>
          </transition-group>
        </div>
      </div>

      <!-- 右侧固定目录 -->
      <div class="toc-container">
        <!-- 在标题输入框下方添加预览按钮 -->
        <div class="preview-button-container">
          <el-button type="primary" @click="previewTravelJournal">
            <i class="el-icon-view"></i> 预览游记
          </el-button>
        </div>
        <div class="toc-inner">
          <h3 class="toc-header">目录</h3>
          <ul class="toc-list">
            <li v-for="(heading, index) in tableOfContents" :key="index" :class="heading.level">
              <a
                  @click.prevent="scrollToHeading(heading.id)"
                  href="#"
                  :class="{ 'toc-h1': heading.level === 'h1', 'toc-h2': heading.level === 'h2' }"
              >
                {{ heading.title || '无标题' }}
              </a>
              <!-- 显示子标题列表 -->
              <ul v-if="heading.children && heading.children.length > 0" class="toc-sublist">
                <li v-for="(child, childIndex) in heading.children" :key="childIndex">
                  <a
                      @click.prevent="scrollToHeading(child.id)"
                      href="#"
                      class="toc-h3"
                  >
                    {{ child.title || '无标题' }}
                  </a>
                </li>
              </ul>
            </li>
          </ul>
        </div>
      </div>
    </div>

    <!-- 修改设置弹窗 -->
    <div v-if="showSettings" class="settings-modal">
      <div class="settings-content">
        <h3>设置段落格式</h3>
        <div class="format-options">
          <!-- 文本标题选项 -->
          <button @click="setParagraphFormat('text', 'h1')">
            <i class="el-icon-edit"></i> 一级标题
          </button>
          <button @click="setParagraphFormat('text', 'h2')">
            <i class="el-icon-edit"></i> 二级标题
          </button>
          <button @click="setParagraphFormat('text', 'h3')">
            <i class="el-icon-edit"></i> 三级标题
          </button>
          <!-- 其他段落类型选项 -->
          <button @click="setParagraphFormat('tip')">
            <i class="el-icon-info"></i> 小贴士
          </button>
          <button @click="setParagraphFormat('quote')">
            <i class="el-icon-quote"></i> 名人名言
          </button>
          <button @click="setParagraphFormat('image')">
            <i class="el-icon-picture"></i> 图片组
          </button>
          <button @click="setParagraphFormat('video')">
            <i class="fas fa-video"></i> 视频
          </button>
        </div>
        <button class="close-button" @click="closeSettings">关闭</button>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from "@/components/NavBar.vue";

export default {
  name: "TravelJournalEditor",
  components: {NavBar},
  data() {
    return {
      selectedTags: [], // 已选择的标签
      showTagSelector: false, // 是否显示标签选择器
      tagFilter: '', // 标签筛选关键词
      transferValue: [], // 存储穿梭框选中的标签key数组
      // 预定义的标签库
      tagLibrary: [
        {id: 1, name: '三亚', type: ''},
        {id: 2, name: '海岛', type: 'info'},
        {id: 3, name: '美食', type: 'success'},
        {id: 4, name: '摄影', type: 'warning'},
        {id: 5, name: '自由行', type: 'danger'},
        {id: 6, name: '古镇', type: ''},
        {id: 7, name: '山水', type: 'info'},
        {id: 8, name: '亲子', type: 'success'},
        {id: 9, name: '人文', type: 'warning'},
        {id: 10, name: '城市', type: 'danger'},
        {id: 11, name: '购物', type: ''},
        {id: 12, name: '徒步', type: 'info'},
        {id: 13, name: '自驾', type: 'success'},
      ],
      tags: [],
      inputTag: '',
      tagColors: ['', 'info', 'success', 'warning', 'danger'],
      imageLayouts: [
        { value: 'single', label: '单图', icon: 'el-icon-picture' },
        { value: 'double', label: '双图', icon: 'el-icon-picture-outline' },
        { value: 'triple', label: '三图', icon: 'el-icon-picture-outline-round' },
        { value: 'quad', label: '四图', icon: 'el-icon-copy-document' }
      ],
      activeComponent:'travelogue',
      // 封面图片URL
      coverImage: "",
      // 标题
      title: "",
      titleFocused: false,
      // 段落数组 - 初始只有一个普通段落
      paragraphs: [
        {
          type: "text",
          format: "normal",
          content: "",
        }
      ],
      // 设置弹窗
      showSettings: false,
      currentParagraphIndex: null,
      // 拖拽相关
      draggedIndex: null,
      dropIndex: null,
      isDragging: false,
    };
  },
  created() {
    // 检查是否有从预览页面返回的数据
    const returnData = sessionStorage.getItem('returnEditData');

    if (returnData) {
      try {
        const editData = JSON.parse(returnData);
        // 用返回的数据更新编辑器状态
        this.title = editData.title || '';
        this.coverImage = editData.coverImage || '';
        this.selectedTags = editData.selectedTags || [];
        this.paragraphs = editData.paragraphs || [{
          type: "text",
          format: "normal",
          content: ""
        }];

        // 使用完毕后清除数据，避免影响下次编辑
        sessionStorage.removeItem('returnEditData');

        console.log('已从预览页面恢复编辑状态');
      } catch (error) {
        console.error('解析返回编辑数据失败:', error);
        // 解析失败则获取随机封面图片
        this.getRandomCoverImage();
      }
    } else {
      // 没有返回数据，执行正常的初始化
      this.getRandomCoverImage();
    }
  },
  computed: {
    // 根据筛选条件过滤可用标签
    filteredTags() {
      // 过滤已选择的标签和符合搜索条件的标签
      return this.tagLibrary.filter(tag => {
        // 检查标签是否已被选择
        const isSelected = this.selectedTags.some(selectedTag => selectedTag.id === tag.id);

        // 如果已选择，则排除
        if (isSelected) return false;

        // 如果有搜索关键词，则根据关键词筛选
        if (this.tagFilter) {
          return tag.name.toLowerCase().includes(this.tagFilter.toLowerCase());
        }

        // 否则返回所有未选择的标签
        return true;
      });
    },
    // 生成目录
    tableOfContents() {
      const toc = [];
      let currentH1 = null;
      let currentH2 = null;

      this.paragraphs.forEach((paragraph, index) => {
        if (paragraph.type === 'text') {
          if (paragraph.format === 'h1') {
            // 新的一级标题
            currentH1 = {
              id: `paragraph-${index}`,
              title: paragraph.content,
              level: 'h1',
              children: []
            };
            currentH2 = null;
            toc.push(currentH1);
          } else if (paragraph.format === 'h2') {
            // 二级标题
            currentH2 = {
              id: `paragraph-${index}`,
              title: paragraph.content,
              level: 'h2',
              children: []
            };

            // 如果有父级标题，添加为子项
            if (currentH1) {
              currentH1.children.push(currentH2);
            } else {
              // 没有父级标题，直接添加到toc
              toc.push(currentH2);
            }
          } else if (paragraph.format === 'h3') {
            // 三级标题
            const h3Item = {
              id: `paragraph-${index}`,
              title: paragraph.content,
              level: 'h3'
            };

            // 如果有上级h2标题，添加到h2下
            if (currentH2) {
              if (!currentH2.children) {
                currentH2.children = [];
              }
              currentH2.children.push(h3Item);
            }
            // 如果只有h1没有h2，添加到h1下
            else if (currentH1) {
              currentH1.children.push(h3Item);
            }
            // 没有任何上级标题，直接添加到toc
            else {
              toc.push(h3Item);
            }
          }
        }
      });

      return toc;
    }
  },
  mounted() {
    // 初始化时获取随机封面图片
    this.getRandomCoverImage();
  },
  methods: {
    // 显示弹出框
    showDialog(){
      this.showTagSelector = true
    },
    // 添加标签
    selectTag(tag) {
      this.selectedTags.push({...tag});
      this.tagFilter = ''; // 清空搜索条件
    },

    // 移除标签
    removeTag(index) {
      this.selectedTags.splice(index, 1);
    },
    // 游记预览功能
    previewTravelJournal() {
      // 构建与游记页面兼容的数据结构
      const previewData = {
        id: Date.now(), // 临时ID
        title: this.title || "未命名游记",
        coverImage: this.coverImage || "https://picsum.photos/1200/400", // 默认封面
        publishDate: new Date().toISOString().slice(0, 10),
        views: 0,
        likes: 0,
        commentCount: 0,
        author: {
          id: 101,
          name: "当前用户",
          avatar: "https://randomuser.me/api/portraits/women/68.jpg",
          bio: "游记作者",
          articles: 1,
          followers: 0,
          totalLikes: 0
        },
        tags: this.selectedTags.length > 0 ? this.selectedTags : [
          {id: 1, name: '游记', type: ''}
        ],
        content: this.transformContentForPreview()
      };

      // 将数据存储到localStorage或sessionStorage
      sessionStorage.setItem('previewTravelJournal', JSON.stringify(previewData));

      // 跳转到预览页面
      // window.open('/travel-blog?preview=true', '_blank');
      // 跳转到预览页面
      this.$router.push({ path: '/travelBlogPage', query: { preview: 'true' } });
    },

// 转换编辑器内容为游记页面所需格式
    transformContentForPreview() {
      const content = [];
      let currentSection = null;
      let sectionIndex = 0;

      // 遍历段落，组织成节(section)和内容(content)的格式
      this.paragraphs.forEach((paragraph, index) => {
        // 一级标题作为新的section
        if (paragraph.type === 'text' && paragraph.format === 'h1') {
          // 如果已经有section，先保存它
          if (currentSection) {
            content.push(currentSection);
          }

          // 创建新的section
          currentSection = {
            title: paragraph.content,
            content: []
          };
          sectionIndex++;
        }
        // 其他内容添加到当前section
        else {
          // 如果还没有section，创建一个默认的
          if (!currentSection) {
            currentSection = {
              title: '游记正文',
              content: []
            };
            sectionIndex++;
          }

          // 根据段落类型添加内容
          switch (paragraph.type) {
            case 'text':
              if (paragraph.format === 'h2' || paragraph.format === 'h3') {
                currentSection.content.push({
                  type: 'subtitle',
                  content: paragraph.content
                });
              } else {
                currentSection.content.push({
                  type: 'text',
                  content: paragraph.content
                });
              }
              break;
            case 'tip':
              currentSection.content.push({
                type: 'tip',
                content: paragraph.content
              });
              break;
            case 'quote':
              currentSection.content.push({
                type: 'quote',
                content: paragraph.content,
                author: paragraph.author || ''
              });
              break;
            case 'image':
              // 根据图片布局决定是单张图片还是图片组
              // eslint-disable-next-line no-case-declarations
              const imageCount = this.getImageCountForLayout(paragraph.layout);
              // eslint-disable-next-line no-case-declarations
              const validImages = paragraph.images
                  .slice(0, imageCount)
                  .filter(img => img.url); // 只包含有URL的图片

              if (validImages.length === 1) {
                // 单张图片
                currentSection.content.push({
                  type: 'image',
                  url: validImages[0].url,
                  caption: validImages[0].caption || ''
                });
              } else if (validImages.length > 1) {
                // 多张图片作为图片组
                currentSection.content.push({
                  type: 'imageGroup',
                  images: validImages.map(img => ({
                    url: img.url,
                    caption: img.caption || ''
                  }))
                });
              }
              break;
            case 'video':
              if (paragraph.content) {
                currentSection.content.push({
                  type: 'video',
                  url: paragraph.content,
                  caption: ''
                });
              }
              break;
          }
        }
      });

      // 添加最后一个section
      if (currentSection) {
        content.push(currentSection);
      }

      return content;
    },
    // 获取段落ID
    getParagraphId(paragraph, index) {
      return `paragraph-${index}`;
    },

    // 根据布局类型获取应显示的图片数量
    getImageCountForLayout(layout) {
      switch(layout) {
        case 'single': return 1;
        case 'double': return 2;
        case 'triple': return 3;
        case 'quad': return 4;
        default: return 1;
      }
    },

    // 改变图片布局
    changeImageLayout(paragraph, newLayout) {
      paragraph.layout = newLayout;
      // 确保图片数组长度符合需求
      const requiredCount = this.getImageCountForLayout(newLayout);
      if (paragraph.images.length < requiredCount) {
        // 如果图片数量不够，添加空图片对象
        for (let i = paragraph.images.length; i < requiredCount; i++) {
          paragraph.images.push({ url: "", caption: "" });
        }
      }
    },

    // 滚动到指定标题
    scrollToHeading(id) {
      const element = document.getElementById(id);
      if (element) {
        element.scrollIntoView({ behavior: 'smooth', block: 'start' });
      }
    },

    // 获取随机封面图片
    getRandomCoverImage() {
      // 这里应该是从后端API获取随机图片
      // 这里用占位图示例
      this.coverImage = "https://picsum.photos/1200/400";
    },

    // 触发封面上传
    triggerCoverUpload() {
      this.$refs.coverUpload.click();
    },

    // 处理封面上传
    handleCoverUpload(event) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.coverImage = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },

    // 聚焦标题输入框
    focusTitle() {
      this.$refs.titleInput.focus();
    },

    // 处理标题失焦
    handleTitleBlur() {
      this.titleFocused = this.title.length > 0;
    },

    // 添加新段落 - 默认为普通文本段落
    addParagraph(index) {
      const newParagraph = {
        type: "text",
        format: "normal",
        content: "",
      };
      this.paragraphs.splice(index + 1, 0, newParagraph);
    },

    // 删除段落
    deleteParagraph(index) {
      // 防止删除最后一个段落
      if (this.paragraphs.length > 1) {
        // 添加淡出动画效果
        const paragraphElement = document.getElementById(`paragraph-${index}`);
        paragraphElement.classList.add('fade-out');

        // 等待动画完成后删除
        setTimeout(() => {
          this.paragraphs.splice(index, 1);
        }, 300);
      }
    },

    // 上移/下移段落
    moveParagraph(index, direction) {
      const newIndex = index + direction;

      // 确保新位置有效
      if (newIndex >= 0 && newIndex < this.paragraphs.length) {
        // 存储要移动的段落
        const paragraph = this.paragraphs[index];

        // 从数组中移除
        this.paragraphs.splice(index, 1);

        // 插入到新位置
        this.paragraphs.splice(newIndex, 0, paragraph);
      }
    },

    // 开始拖拽
    startDrag(event, index) {
      this.draggedIndex = index;
      this.isDragging = true;

      // 设置拖拽图像（可选，使用透明图像以便自定义样式）
      const dragImage = new Image();
      dragImage.src = ''; // 透明1px图像
      event.dataTransfer.setDragImage(dragImage, 0, 0);

      // 设置拖拽数据
      event.dataTransfer.effectAllowed = 'move';
      event.dataTransfer.setData('text/plain', index.toString());

      // 添加拖拽样式
      event.target.classList.add('dragging');
    },

    // 拖拽经过某元素时
    onDragOver(event, index) {
      event.dataTransfer.dropEffect = 'move';
      // 这里可以添加视觉提示效果
    },

    // 拖拽进入某元素
    onDragEnter(event, index) {
      if (this.draggedIndex !== index) {
        this.dropIndex = index;
        event.currentTarget.classList.add('drag-over');
      }
    },

    // 拖拽离开某元素
    onDragLeave(event) {
      event.currentTarget.classList.remove('drag-over');
    },

    // 放置
    onDrop(event, index) {
      event.currentTarget.classList.remove('drag-over');

      if (this.draggedIndex !== index) {
        // 获取拖拽的段落
        const draggedParagraph = this.paragraphs[this.draggedIndex];

        // 从原位置删除
        this.paragraphs.splice(this.draggedIndex, 1);

        // 插入到新位置
        this.paragraphs.splice(index, 0, draggedParagraph);
      }
    },

    // 结束拖拽
    endDrag() {
      this.draggedIndex = null;
      this.dropIndex = null;
      this.isDragging = false;

      // 移除所有拖拽相关的类
      document.querySelectorAll('.drag-over').forEach(el => {
        el.classList.remove('drag-over');
      });
      document.querySelectorAll('.dragging').forEach(el => {
        el.classList.remove('dragging');
      });
    },

    // 打开段落设置
    openSettings(index) {
      this.currentParagraphIndex = index;
      this.showSettings = true;
    },

    // 关闭段落设置
    closeSettings() {
      this.showSettings = false;
    },

    // 设置段落格式
    setParagraphFormat(type, format = null) {
      const index = this.currentParagraphIndex;
      let newPara;

      if (type === 'text') {
        // 文本段落，可以有不同的标题格式
        newPara = {
          type: "text",
          format: format || "normal",
          content: this.paragraphs[index].content || "",
        };
      } else if (type === 'image') {
        // 图片段落，默认为单图
        newPara = {
          type: "image",
          layout: "single", // 默认单图布局
          images: [
            { url: "", caption: "" } // 只初始化一个图片位置
          ]
        };
      } else if (type === 'quote') {
        // 名言段落
        newPara = {
          type: "quote",
          content: "",
          author: ""
        };
      } else if (type === 'tip') {
        // 小贴士段落
        newPara = {
          type: "tip",
          content: ""
        };
      } else if (type === 'video') {
        // 视频段落
        newPara = {
          type: "video",
          content: ""
        };
      }

      // 替换当前段落
      this.paragraphs.splice(index, 1, newPara);
      this.closeSettings();
    },

    // 触发图片上传
    triggerImageUpload(paraIndex, imgIndex) {
      // 使用 $nextTick 确保 DOM 已更新
      this.$nextTick(() => {
        if (this.$refs[`imageUpload${paraIndex}_${imgIndex}`]) {
          this.$refs[`imageUpload${paraIndex}_${imgIndex}`][0].click();
        }
      });
    },

    // 处理图片上传
    handleImageUpload(event, paraIndex, imgIndex) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.paragraphs[paraIndex].images[imgIndex].url = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },

    // 触发视频上传
    triggerVideoUpload(index) {
      this.$nextTick(() => {
        if (this.$refs[`videoUpload${index}`]) {
          this.$refs[`videoUpload${index}`][0].click();
        }
      });
    },

    // 处理视频上传
    handleVideoUpload(event, index) {
      const file = event.target.files[0];
      if (file) {
        const reader = new FileReader();
        reader.onload = (e) => {
          this.paragraphs[index].content = e.target.result;
        };
        reader.readAsDataURL(file);
      }
    },
  },
};
</script>

<style scoped>
/* 标签选择区域样式 */
.tags-container {
  margin-bottom: 20px;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 10px;
}

.select-tags-button {
  padding: 8px 16px;
  background: #409EFF;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  font-size: 14px;
}

.select-tags-button i {
  margin-right: 5px;
}

.tag-search {
  margin-bottom: 15px;
}

.tag-search-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.tag-options {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  max-height: 300px;
  overflow-y: auto;
  padding: 10px 0;
}

.tag-option {
  cursor: pointer;
  transition: all 0.2s;
}

.tag-option:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.no-tags-found {
  width: 100%;
  text-align: center;
  padding: 20px;
  color: #999;
  font-style: italic;
}
.preview-button-container {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}
.tip-editor {
  background: #ecf8ff;
  border-radius: 8px;
  padding: 15px;
  border: 1px dashed #409EFF;
}

.tip-header {
  color: #409EFF;
  margin-bottom: 10px;
}

.quote-editor {
  border-left: 4px solid #409EFF;
  padding: 15px 20px;
  background: #f8f9fa;
}

.author-input {
  margin-top: 10px;
  width: 100%;
  padding: 5px;
  border: 1px solid #ddd;
}

.image-editor {
  border: 1px dashed #ddd;
  padding: 15px;
  border-radius: 8px;
}

.layout-selector {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.layout-selector button {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  background: white;
}

.layout-selector button.active {
  border-color: #409EFF;
  background: #ecf8ff;
}

.image-grid {
  display: grid;
  gap: 10px;
}

.layout-single { grid-template-columns: 1fr; }
.layout-double { grid-template-columns: repeat(2, 1fr); }
.layout-triple { grid-template-columns: repeat(3, 1fr); }
.layout-quad { grid-template-columns: repeat(2, 1fr); }

.image-item .image-wrapper {
  aspect-ratio: 1;
  border: 2px dashed #ddd;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
}
.fit-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

.upload-area {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #999;
}

.caption-input {
  width: 100%;
  padding: 5px;
  font-size: 12px;
  border: 1px solid #eee;
}
.travel-journal-editor {
  width: 100%;
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
  background-color: #f9f9f9;
}

/* 封面区域样式 - 仍然是100%宽度 */
.cover-container {
  width: 100%;
  height: 450px;
  position: relative;
  margin-bottom: 20px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.cover-image {
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-button {
  position: absolute;
  bottom: 20px;
  right: 20px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  font-weight: bold;
  box-shadow: 0 2px 5px rgba(0,0,0,0.2);
  transition: all 0.3s;
}

.upload-button:hover {
  background-color: #ff5252;
  transform: translateY(-2px);
}

.hidden-input {
  display: none;
}

/* 新增布局容器 */
.editor-layout {
  max-width: 1400px;
  margin: 0 auto;
  display: flex;
  position: relative;
  padding: 0 20px;
}

/* 正文区域样式 - 变窄了 */
.content-container {
  width: 70%;
  padding: 20px 30px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 2px 15px rgba(0,0,0,0.05);
}

/* 标题区域样式 */
.title-container {
  margin-bottom: 30px;
  border-bottom: 2px solid #f0f0f0;
}

.title-input {
  width: 100%;
  font-size: 36px;
  font-weight: bold;
  padding: 10px 0;
  border: none;
  outline: none;
  color: #333;
}

.title-input::placeholder {
  color: #aaa;
}

/* 段落块样式 */
.paragraph-block {
  display: flex;
  margin-bottom: 25px;
  scroll-margin-top: 100px; /* 为滚动定位添加margin */
  padding: 15px;
  border-radius: 8px;
  transition: all 0.3s ease;
  position: relative;
}

.paragraph-block:hover {
  background-color: rgba(0, 0, 0, 0.02);
}

.paragraph-block.is-dragging {
  opacity: 0.5;
  transform: scale(0.98);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  background-color: #f8f8f8;
}

.paragraph-block.drag-over {
  border: 2px dashed #ff6b6b;
  padding: 13px; /* 调整内边距保持总大小不变 */
  background-color: rgba(255, 107, 107, 0.05);
}

/* 拖拽动画 */
.paragraph-move-enter-active,
.paragraph-move-leave-active {
  transition: all 0.5s ease;
}

.paragraph-move-enter-from,
.paragraph-move-leave-to {
  opacity: 0;
  transform: translateY(30px);
}

.paragraph-move-leave-active {
  position: absolute;
}

.fade-out {
  animation: fadeOut 0.3s forwards;
}

@keyframes fadeOut {
  from { opacity: 1; transform: translateY(0); }
  to { opacity: 0; transform: translateY(-10px); }
}

.paragraph-tools {
  display: flex;
  flex-direction: column;
  margin-right: 15px;
}

.tool-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 1px solid #ddd;
  background-color: white;
  margin-bottom: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
  color: #666;
}

.tool-button:hover {
  background-color: #f0f0f0;
  transform: scale(1.05);
}

.tool-button:disabled {
  opacity: 0.4;
  cursor: not-allowed;
  transform: none;
}

.drag-button {
  cursor: grab;
  color: #555;
}

.drag-button:active {
  cursor: grabbing;
}

.move-up, .move-down {
  background-color: #f8f8f8;
}

.move-up:hover, .move-down:hover {
  background-color: #eaeaea;
}

.delete-button {
  color: #ff6b6b;
}

.delete-button:hover {
  background-color: #fff0f0;
}

.paragraph-content {
  flex: 1;
}

/* 文本段落样式 */
.paragraph-textarea {
  width: 90%;
  min-height: 150px;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  outline: none;
  resize: vertical;
  font-size: 16px;
  line-height: 1.6;
  transition: border 0.3s;
}

.paragraph-textarea:focus {
  border-color: #ff6b6b;
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.1);
}

/* 标题样式 */
.heading-h1 {
  font-size: 28px;
  font-weight: bold;
  color: #333;
}

.heading-h2 {
  font-size: 24px;
  font-weight: bold;
  color: #444;
}

.heading-h3 {
  font-size: 20px;
  font-weight: bold;
  color: #555;
}

.heading-textarea {
  width: 90%;
  padding: 15px;
  border: 1px solid #eee;
  border-radius: 8px;
  outline: none;
  resize: vertical;
  line-height: 1.3;
  transition: border 0.3s;
}

.heading-textarea:focus {
  border-color: #ff6b6b;
  box-shadow: 0 0 0 2px rgba(255, 107, 107, 0.1);
}

/* 图片段落样式 */
.image-paragraph {
  width: 100%;
}

.image-upload {
  width: 100%;
  height: 200px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s;
}

.image-upload:hover {
  border-color: #ff6b6b;
  background-color: rgba(255, 107, 107, 0.03);
}

.image-upload i {
  font-size: 48px;
  margin-bottom: 10px;
}

.image-preview {
  width: 100%;
}

.image-preview img {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

/* 视频段落样式 */
.video-paragraph {
  width: 100%;
}

.video-upload {
  width: 100%;
  height: 200px;
  border: 2px dashed #ddd;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: #999;
  transition: all 0.3s;
}

.video-upload:hover {
  border-color: #ff6b6b;
  background-color: rgba(255, 107, 107, 0.03);
}

.video-upload i {
  font-size: 48px;
  margin-bottom: 10px;
}

.video-preview {
  width: 100%;
}

.video-preview video {
  max-width: 100%;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

/* 设置弹窗样式 */
.settings-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(3px);
}

.settings-content {
  background-color: white;
  padding: 30px;
  border-radius: 12px;
  width: 400px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.2);
  animation: modalFadeIn 0.3s;
}

@keyframes modalFadeIn {
  from { opacity: 0; transform: translateY(-20px); }
  to { opacity: 1; transform: translateY(0); }
}

.settings-content h3 {
  margin-top: 0;
  margin-bottom: 20px;
  text-align: center;
  color: #333;
}

.format-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  margin-bottom: 25px;
}

.format-options button {
  padding: 12px 15px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
}

.format-options button:hover {
  background-color: #f5f5f5;
  border-color: #ccc;
}

.close-button {
  width: 100%;
  padding: 12px;
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s;
}

.close-button:hover {
  background-color: #ff5252;
}

/* 新增：目录容器样式 */
.toc-container {
  width: 25%;
  margin-left: 5%;
  position: relative;
}

.toc-inner {
  position: sticky;
  top: 30px;
  background-color: white;
  border-radius: 10px;
  padding: 20px;
}
</style>